package com.hjx.windowtool.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

public class ImgUtil {
	public static void randomMarkImage(String src,String out,double min, double max,int size,String fomatName) throws IOException{
		File file = new File(src);
		BufferedImage image = randomMarkImage(file, min, max, size);
		ImageIO.write(image, fomatName, new File(out,file.getName().substring(0, file.getName().lastIndexOf("."))+"."+fomatName));
	}
	public static BufferedImage randomMarkImage(File file, double min, double max,int size) {
		try {
			if (!file.isFile()) {
				return null;
			}
			BufferedImage img = ImageIO.read(file); // 读取该图片
			int width = img.getWidth(null); // 原图片宽
			int height = img.getHeight(null); // 原图片高
			// 马赛克格尺寸太大或太小
			if (width < size || height < size) {
				return null;
			}
			if (size <= 0) {
				return null;
			}
			int wmin=(int) (width*min);
			int wmax=(int) (width*max);
			int hmin=(int) (height*min);
			int hmax=(int) (height*max);
			
			
			Random random = new Random();
			int mskwidth=wmin+random.nextInt(wmax-wmin);
			int mskheight=hmin+random.nextInt(hmax-hmin);
			int xcount = 0; // x方向绘制个数
			int ycount = 0; // y方向绘制个数
			if (mskwidth % size == 0) {
				xcount = mskwidth / size;
			} else {
				xcount = mskwidth / size + 1;
			}
			if (mskheight % size == 0) {
				ycount = mskheight / size;
			} else {
				ycount = mskheight / size + 1;
			}
			int x = random.nextInt(width-mskwidth); // x坐标
			int y = random.nextInt(height-mskheight); // y坐标
			
			BufferedImage bi = maskImage(size, img, x, y, mskwidth, mskheight);
			return bi;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * @param size
	 * @param img
	 * @param width
	 * @param height
	 * @param mskwidth
	 * @param mskheight
	 * @param x
	 * @param y
	 * @return
	 */
	public static BufferedImage maskImage(int size, BufferedImage img, int x, int y,int mskwidth, int mskheight) {
		int width = img.getWidth(null); // 原图片宽
		int height = img.getHeight(null); // 原图片高
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				bi.setRGB(i, j, img.getRGB(i, j));
			}
		}
		// 绘制马赛克(绘制矩形并填充颜色)
		Graphics2D g = bi.createGraphics();
		
		System.out.println(x+"=="+y+"=="+mskwidth+"=="+mskheight);
		for (int i = x; i < x+mskwidth;i+=size) {
			for (int j = y; j < y+mskheight;j+=size) {
				// msk矩形格大小
				int mwidth = size;
				int mheight = size;
				// 矩形颜色取中心像素点RGB值
				int centerX = i;
				int centerY = j;
				if (mwidth % 2 == 0) {
					centerX += mwidth / 2;
				} else {
					centerX += (mwidth - 1) / 2;
				}
				if (mheight % 2 == 0) {
					centerY += mheight / 2;
				} else {
					centerY += (mheight - 1) / 2;
				}
				if (centerX>=width||centerY>=height) {
					continue;
				}
				Color color = new Color(img.getRGB(centerX, centerY));
				g.setColor(color);
				g.fillRect(i, j, mwidth, mheight);
			}
		}
		g.dispose();
		return bi;
	}

	public static String markImageByMosaic(String source, String output, String imageName, String imageType, int size) {
		String result = "图片打马赛克出错";
		try {
			File file = new File(source);
			if (!file.isFile()) {
				return file + " 不是一个图片文件!";
			}
			BufferedImage img = ImageIO.read(file); // 读取该图片
			int width = img.getWidth(null); // 原图片宽
			int height = img.getHeight(null); // 原图片高
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			// 马赛克格尺寸太大或太小
			if (width < size || height < size) {
				return "马赛克格尺寸太大";
			}
			if (size <= 0) {
				return "马赛克格尺寸太小";
			}
			int xcount = 0; // x方向绘制个数
			int ycount = 0; // y方向绘制个数
			if (width % size == 0) {
				xcount = width / size;
			} else {
				xcount = width / size + 1;
			}
			if (height % size == 0) {
				ycount = height / size;
			} else {
				ycount = height / size + 1;
			}
			int x = 0; // x坐标
			int y = 0; // y坐标
			// 绘制马赛克(绘制矩形并填充颜色)
			Graphics2D g = bi.createGraphics();
			
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					bi.setRGB(i, j, img.getRGB(i, j));
				}
			}
			
			for (int i = 0; i < xcount; i++) {
				for (int j = 0; j < ycount; j++) {
					// 马赛克矩形格大小
					int mwidth = size;
					int mheight = size;
					if (i == xcount - 1) { // 横向最后一个不够一个size
						mwidth = width - x;
					}
					if (j == ycount - 1) { // 纵向最后一个不够一个size
						mheight = height - y;
					}
					// 矩形颜色取中心像素点RGB值
					int centerX = x;
					int centerY = y;
					if (mwidth % 2 == 0) {
						centerX += mwidth / 2;
					} else {
						centerX += (mwidth - 1) / 2;
					}
					if (mheight % 2 == 0) {
						centerY += mheight / 2;
					} else {
						centerY += (mheight - 1) / 2;
					}
					Color color = new Color(img.getRGB(centerX, centerY));
					g.setColor(color);
					g.fillRect(x, y, mwidth, mheight);
					y = y + size;// 计算下一个矩形的y坐标
				}
				y = 0;// 还原y坐标
				x = x + size;// 计算x坐标
			}
			g.dispose();
			File sf = new File(output, imageName + "." + imageType);
			ImageIO.write(bi, imageType, sf); // 保存图片
			result = "打马赛克成功";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public static void main(String[] args) throws Exception {
//		markImageByMosaic("D:\\img\\20180601152100463_川S69112_big.jpg", "D:\\img\\", "1", "png", 2);
		randomMarkImage("D:\\img\\20180601152100463_川S69112_big.jpg", "D:\\img\\", 30d/100d,80d/100d, 8, "png");
	}
	public static BufferedImage resizeImage(File file, int width, int height) {
		try {
			if (!file.isFile()||(width<=0&&height<=0)) {
				return null;
			}
			BufferedImage img = ImageIO.read(file); // 读取该图片
			int w = img.getWidth();
			int h = img.getHeight();	
			if (width<=0) {
				
			}
			
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = bi.createGraphics();
			g.drawImage(img, 0, 0, width, height, 0, 0, w, h, null);
			g.dispose();
			return bi;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void saveImage(BufferedImage img,File out,String fomat){
		try {
			if (!out.exists()) {
				out.mkdirs();
			}
			ImageIO.write(img, fomat, out);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Image getImageFromStream(Display display, byte[] imageByte,int width,int height){
		if(imageByte == null || imageByte.length == 0||width==0||height==0){
			return null;
		}
		try(ByteArrayInputStream bais = new ByteArrayInputStream(imageByte)){
			ImageData id = new ImageData(bais).scaledTo(width, height);
			return new Image(display,id);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	public static void setBackgroundImage(Control clabel_entryImg, byte[] entry_img) {
		clabel_entryImg.getDisplay().asyncExec(() -> {
			if (clabel_entryImg == null || clabel_entryImg.isDisposed()) {
				return;
			}
			Image image = null;
			if (entry_img != null){
				Rectangle bounds = clabel_entryImg.getBounds();
				image = getImageFromStream(clabel_entryImg.getDisplay(), entry_img, bounds.width, bounds.height);
			}
			setBackgroud(clabel_entryImg, image);
        });
	}

	public static void setBackgroundImage(Control clabel_entryImg, Image image) {
		clabel_entryImg.getDisplay().asyncExec(() -> setBackgroud(clabel_entryImg, image));
	}

	private static void setBackgroud(Control clabel_entryImg, Image image){
		try {
			if (clabel_entryImg.getBackgroundImage() != null) {
				clabel_entryImg.getBackgroundImage().dispose();
				clabel_entryImg.setBackgroundImage(null);
			}
			if (image != null){
				clabel_entryImg.setBackgroundImage(image);
			}
			if (clabel_entryImg.getData("bindDisposeListen") == null){
				clabel_entryImg.setData("bindDisposeListen",true);
				clabel_entryImg.addDisposeListener(e -> {
					Control source = (Control) e.getSource();
					if (source.getBackgroundImage() != null) {
						source.getBackgroundImage().dispose();
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
